﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Powerpi.Services
{
    /// <summary>
    /// 
    /// </summary>
    public class SerialPortService : IDisposable
    {
        private readonly SerialPort _SerialPort;
        /// <summary>
        /// 返回卡号和COM口
        /// </summary>
        //private Action<byte[]> _Callback;
        private readonly string _PortName;
        /// <summary>
        /// 端口是否打开
        /// </summary>
        public bool IsOpen => _SerialPort.IsOpen;

        public bool IsBusy { get; private set; }
        /// <summary>
        /// 由于设备被拔出等原因，重新打开
        /// </summary>
        /// <returns></returns>
        public bool ReStart()
        {
            if (_SerialPort != null && !_SerialPort.IsOpen && !string.IsNullOrEmpty(_PortName))
            {
                _SerialPort.Open();
                _SerialPort.DiscardInBuffer();
                return true;
            }
            else
                return false;
        }
        public void Close()
        {
            if (_SerialPort.IsOpen)
                _SerialPort.Close();
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="portName">端口号</param>
        /// <param name="baudrate">波特率</param>
        /// <param name="databits">数据位长度</param>
        /// <param name="stopbit">停止位数</param>
        /// <param name="parity">奇偶校验</param>
        public SerialPortService(string portName, int baudrate = 1200, int databits = 8, StopBits stopbit = StopBits.One, Parity parity = Parity.Even)
        {
            _PortName = portName;
            _SerialPort = new SerialPort(portName)
            {
                
                ReadBufferSize = 100,
                Handshake = Handshake.None,
                DtrEnable = true,
                RtsEnable = true,
                Parity = parity,// Parity.None,
                BaudRate = baudrate,// 9600,
                DataBits = databits,//8,
                StopBits = stopbit,//StopBits.One,
                DiscardNull = true,
                ReadTimeout = 3000,
                WriteTimeout = 3000,
                Encoding = Encoding.UTF8
            };
            _SerialPort.DiscardNull = false;
            //_SerialPort.DataReceived += SerialPort_DataReceived;

        }

        /// <summary>
        /// 打卡端口监听，并回调返回数据
        /// </summary>
        /// <param name="action">回调事件(卡号，端口号)</param>
        /// <returns>成功返回Success,失败返回错误信息</returns>
        public string Start()
        {
            string result = "Success";
            try
            {
                _SerialPort.Open();
                _SerialPort.DiscardInBuffer();
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 打卡端口监听，并回调返回数据
        /// </summary>
        /// <param name="action">回调事件(卡号，端口号)</param>
        /// <returns>成功返回Success,失败返回错误信息</returns>
        //public string Start(Action<byte[]> action)
        //{
        //    _Callback = action;
        //    string result = "Success";
        //    try
        //    {
        //        _SerialPort.Open();
        //        _SerialPort.DiscardInBuffer();
        //    }
        //    catch (Exception ex)
        //    {
        //        result = ex.Message;
        //    }
        //    return result;
        //}
        public void Stop()
        {
            if (_SerialPort.IsOpen)
                _SerialPort.Close();
            _SerialPort.Dispose();
        }
        public byte[] Send(byte[] buf)
        {
            IsBusy = true;
            if (_SerialPort.IsOpen)
            {
                //Clear in/out buffers:
                _SerialPort.DiscardOutBuffer();//清空发送、接收缓冲区字节
                _SerialPort.DiscardInBuffer();
                _SerialPort.Write(buf, 0, buf.Length);

                Task.Delay(500).Wait();
                //byte[] receivedData = new byte[22];        //创建接收字节数组
                byte[] receivedData = new byte[_SerialPort.BytesToRead];        //创建接收字节数组
                _SerialPort.Read(receivedData, 0, receivedData.Length);         //读取数据
                _SerialPort.DiscardOutBuffer();
                _SerialPort.DiscardInBuffer();
                return receivedData;
            }
            IsBusy = false;
            return null;
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (_SerialPort.IsOpen)
            {
                Task.Delay(1000).Wait();
                byte[] receivedData = new byte[_SerialPort.BytesToRead];        //创建接收字节数组
                _SerialPort.Read(receivedData, 0, receivedData.Length);         //读取数据
                _SerialPort.DiscardOutBuffer();
                _SerialPort.DiscardInBuffer();
                //_Callback(receivedData);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            _SerialPort.Close();
            _SerialPort.Dispose();
        }
    }
}
